package com.aat.dxfy.iparea;

import java.io.IOException;
import java.util.Arrays;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.perf4j.StopWatch;
import org.perf4j.slf4j.Slf4JStopWatch;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * QPS 500 企业版
 * 
 * @author Administrator
 *
 */
public class GaodeAPI {

	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			System.out.println(Arrays.toString(getCityAndCode("118.28.8.8")));
		}
	}

	public static String[] getCityAndCode(String ip) {
		StopWatch stopWatch = new Slf4JStopWatch("gaode api");
		String[] cityS = null;
		String[] keys = { "92af9c0b9d0a084cda2399bb45ae8d61", "95028aa64b13b431327c9fe54fa5de2c",
				"92af9c0b9d0a084cda2399bb45ae8d61", "95028aa64b13b431327c9fe54fa5de2c" };

		int i = (int) (Math.random() * keys.length);
		System.out.println(i);
		String key = keys[i];
		System.out.println(key);
		String url = "http://restapi.amap.com/v3/ip?key=" + key + "&ip=" + ip;

		CloseableHttpClient client = HttpClients.createDefault(); // HttpClientConnectionManagerWrapper.getHttpClient();
		CloseableHttpResponse resp = null;
		HttpGet get = new HttpGet(url);

		try {
			get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0");
			get.addHeader("Accept-Encoding", "gzip, deflate");
			resp = client.execute(get);

			if (resp.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = resp.getEntity();
				String res = EntityUtils.toString(entity);
				System.out.println(res);
				EntityUtils.consume(entity);

				JSONObject jobj = JSON.parseObject(res);
				if (jobj.getInteger("status") == 1) {
					String cityC = jobj.getString("adcode");
					String cityU = jobj.getString("city");
					cityS = new String[] { cityC, cityU };

				}
			}

		} catch (IOException e) {
		} finally {
			try {
				if (get != null)
					get.releaseConnection();
				if (resp != null)
					resp.close();
				if (client != null)
					client.close();
			} catch (IOException e) {
			}
		}
		stopWatch.stop();
		return cityS;
	}

	public static String convert(String utfstr) {
		StringBuilder sb = new StringBuilder();
		int i = -1;
		int pos = 0;
		while ((i = utfstr.indexOf("\\u", pos)) != -1) {
			sb.append(utfstr.substring(pos, i));
			if (i + 5 < utfstr.length()) {
				pos = i + 6;
				sb.append((char) Integer.parseInt(utfstr.substring(i + 2, i + 6), 16));
			}
		}
		return sb.toString();
	}

}
